/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="task-detail-registry__container">
        <!-- <sf-button class="btn-blank creat-button"
                   icon-cls="iconrefresh"
                   @click="refreshGrid">
            <lang>刷新</lang>
        </sf-button> -->
        <div
            class="task-detail__charts">
            <div class="detail-charts__item">
                <div class="title">
                    <lang>准确率对比(%)：</lang>
                </div>
                <sf-e-charts ref="barChart"
                             :options="accurateBarOptions"
                             :auto-destroy="true"
                             :auto-refresh="true"
                             :default-width="660"
                             :default-height="300" />
            </div>
            <div class="detail-charts__item">
                <div class="title">
                    <lang>训练时间对比(s)：</lang>
                </div>
                <sf-e-charts ref="timeBarChart"
                             :options="timeOptions"
                             :auto-destroy="true"
                             :auto-refresh="true"
                             :default-width="660"
                             :default-height="300" />
            </div>
        </div>
        <div class="title m-a10">
            <lang>总体概览：</lang>
        </div>
        <div class="table-data">
            <sf-grid>
                <sf-table 
                    ref="table" 
                    :options="options_fix">
                    <sf-table-column :default-width="30"
                                     type="index">
                        <lang>序号</lang>
                    </sf-table-column>
                    <sf-table-column data-index="name"
                                     :default-width="60">
                        <lang>算法</lang>
                    </sf-table-column>
                    <sf-table-column data-index="accurate"
                                     :default-width="40">
                        <lang>准确率</lang>
                    </sf-table-column>
                    <sf-table-column data-index="time"
                                     :default-width="40">
                        <lang>算法运行时间</lang>
                    </sf-table-column>
                    <sf-table-column data-index="metricsParams"
                                     :default-width="120">
                        <lang>性能指标</lang>
                    </sf-table-column>
                    <!-- <sf-table-column data-index="status"
                                     :default-width="60">
                        <lang>状态</lang>
                    </sf-table-column> -->
                    <sf-table-column data-index="opr"
                                     :default-width="60">
                        <lang>操作</lang>
                    </sf-table-column>
                    <template slot="accurate"
                              slot-scope="{record}">
                        <span>{{ accurateTranslate(record) }}</span>
                    </template>
                    <template slot="time"
                              slot-scope="{record}">
                        <span>{{ timeTranslate(record) }}</span>
                    </template>
                    <template slot="metricsParams"
                              slot-scope="{record}">
                        <span :title="metricsParamsTranslate(record)">{{ metricsParamsTranslate(record) }}</span>
                    </template>
                    <!-- <template slot="status"
                              slot-scope="{record}">
                        <div class="task-flex"
                             :class="repositoryStatusClass(record.status)">
                            <span class="status-img task-common"></span>
                            <span class="status-text">{{ repositoryStatusText(record.status) }}</span>
                        </div>
                    </template> -->
                    <template slot="opr"
                              slot-scope="{record}">
                        <div class="opr">
                            <a 
                                :class="{'disabled': !record.metrics}"
                                class="link-btn"
                                @click="_registryModel(record)">
                                <lang>注册模型</lang>
                            </a>
                        </div>
                    </template>
                </sf-table>
            </sf-grid>
        </div>
    </div>
</template>
<script>


import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
const TRAINING_URL = {
    get:trainingUrlAdapter('task/job'),
    delete:trainingUrlAdapter('task/job/run')
};
import store from 'src/vuex/store';
let userID = store.state.userId;

/*训练状态*/
const REPOSITORY_STATUS_TEXT = {
    0:_('任务完成'),
    1:_('任务中'),
    2:_('任务失败')
};
const REPOSITORY_STATUS_CLASS = {
    0:'task-success',
    1:'task-run',
    2:'task-fail'
};

const BAR_WIDTH  = 20;
import registryModelForm from 'src/home/mod_cluster/project_manager/components/common/model/registry_model_form';
import parseJson from 'src/util/parse_json';
const PERCENT = 100;

import { deepClone } from 'src/util/deep_clone';

export default {
    name: 'TaskDetailContainer',
    props:{
        detailData:{
            type:Array,
            default:()=>[]
        },
        registryParams:{
            type:Object
        }
    },
    data () {
        return {
            options_fix: {
                bufferView: false,

                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                selectionHide: true
            },
            jobId:'',
            name:''
            
        };
    },
    computed: {
        projectId () {
            return this.$route.query.projectId || '';
        },
        accurateBarOptions () {
            let xAxisData = this.detailData.map(item=>item.name);
            let seriesData = this.detailData.map(item=>{
                let accurate = item.metrics ? +parseJson(item.metrics).accurate : 0;
                let accurateNumber = accurate * PERCENT;
                return `${accurateNumber.toFixed(0)}`;
            });
            return {
                tooltip: {
                    backgroundColor:'#fff',
                    padding:10,
                    borderWidth:1,
                    borderColor:'#ddd',
                    textStyle:{
                        color:'#5C5C5C'
                    },
                    trigger: 'item',
                    formatter: '{b}: {c}%'
                },
                grid: {
                    left: '0',
                    right: '0',
                    bottom: '4%',
                    top: '10%',
                    containLabel: true
                },
                color:['#3366FF'],
                xAxis: [
                    {
                        type: 'category',
                    
                        data: xAxisData,
                        axisTick:{
                            show:false
                        },
                        axisLine:{
                            lineStyle:{
                                color:'#eee'
                            }
                        },
                        axisLabel:{
                            color:'#14161A'
                        },
                        splitLine:{
                            lineStyle:{
                                color:['#eee']
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLine:{
                            show:false
                        },
                        axisTick:{
                            show:false
                        }
                    }
                ],
                series: [
                    {
                        type: 'bar',
                        data: seriesData,
                        barWidth:BAR_WIDTH,
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                ]
            };
        },
        timeOptions () {
            let xAxisData = this.detailData.map(item=>item.name);
            let seriesData = this.detailData.map(
                    item=>item.metrics ? parseJson(item.metrics).time.toFixed(1) : 0
            );
            return {
                tooltip: {
                    backgroundColor:'#fff',
                    padding:10,
                    borderWidth:1,
                    borderColor:'#ddd',
                    textStyle:{
                        color:'#5C5C5C'
                    },
                    trigger: 'item',
                    formatter: '{b}: {c}s'
                },
                grid: {
                    left: '0',
                    right: '0',
                    bottom: '4%',
                    top: '10%',
                    containLabel: true
                },
                color:['#3366FF'],
                xAxis: [
                    {
                        type: 'category',
                    
                        data: xAxisData,
                        axisTick:{
                            show:false
                        },
                        axisLine:{
                            lineStyle:{
                                color:'#eee'
                            }
                        },
                        axisLabel:{
                            color:'#14161A'
                        },
                        splitLine:{
                            lineStyle:{
                                color:['#eee']
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLine:{
                            show:false
                        },
                        axisTick:{
                            show:false
                        }
                    }
                ],
                series: [
                    {
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'center'
                        },
                        data: seriesData,
                        barWidth:BAR_WIDTH
                    }
                ]
            };
        }
    },
    watch: {

        // jobId () {
        //     this.refreshGrid();
        // },
        detailData () {
            this.refreshGrid();
        }
    },
    methods: {
        accurateTranslate (record) {
            if (!record.metrics) {
                return '-';
            }
            let accurate = +parseJson(record.metrics).accurate;
            let accurateNumber = accurate * PERCENT;
            return `${accurateNumber.toFixed(0)}%`;
        },
        timeTranslate (record) {
            if (!record.metrics) {
                return '-';
            }
            let time = +parseJson(record.metrics).time;
            return `${time.toFixed(1)}s`;
        },
        metricsParamsTranslate (record) {
            if (!record.metrics) {
                return '-';
            };
            let {metrics} = parseJson(record.metrics);
            let str = '';
            for (let i in metrics) {
                if (metrics.hasOwnProperty(i)) {
                    str += `${i} = ${metrics[i]},`;             
                }
            };
            str = str.substr(0, str.length - 1);
            return str || '-';
        },

        // 注册模型弹窗
        _createRegistryModelFormWin () {
            if (!this.registryModelFormWin) {
                this.registryModelFormWin = this.$modal(registryModelForm, {
                    autoDestory: true
                });
            }
            return this.registryModelFormWin;
        },
         _registryModel (record) {
            let formWin = this._createRegistryModelFormWin();
            let registryParams = deepClone(record);
            Object.assign(record, this.registryParams);
            formWin.formRoot.setJsonValue(record);
            record.s3Address = registryParams.s3Address;
            formWin.open({
                title: _('注册模型'),
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    this.getRegistryId(record, ajaxParams, formWin);
                }
            });
        },
        async getRegistryId (record, ajaxParams, formWin) {
            let registryIDURL = trainingUrlAdapter(`user/${userID}/task/run/${record.jobKubeflowId}`);
            let jsonData = await this.$ajax.get(registryIDURL, {jobId:record.jobKubeflowId});
            let {success, msg, data} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('加载数据失败'));
            };
            ajaxParams.runId = data;
            ajaxParams.taskId = ajaxParams.id;
            ajaxParams.s3Address = record.s3Address;
            this.ajaxSubmitRegistryModel(ajaxParams, formWin);
        },
        async ajaxSubmitRegistryModel (params, formWin) {
            params.projectId = this.projectId;
            formWin.$mask();
            const REGISTRY_URL = trainingUrlAdapter(`user/${userID}/model/registry/${params.id}`);
            let jsonData = await this.$ajax.post(REGISTRY_URL, params);
            formWin.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('注册模型失败'));
            }
            this.$ok(_('注册模型成功'));
            formWin.hide();
            this.refreshGrid();
            this.$router.push({
                path:`/project_manager/project_index/model_repository`,
                query:this.$route.query
            });
        },

        // 刷新grid
        refreshGrid () {
            this.$nextTick(()=>{
                let table = this.$refs.table;
                table && table.loadData(this.detailData || []);
            });
        },
        repositoryStatusClass (status) {
            return REPOSITORY_STATUS_CLASS[status];
        },
        repositoryStatusText (status) {
            return REPOSITORY_STATUS_TEXT[status];
        },
        async ajaxDeleteTask (record) {
            const DELETE_URL = `${TRAINING_URL.delete}/${record.id}`;
            this.$mask();
            let jsonData = await this.$ajax.delete(DELETE_URL, record);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.$ok(_('删除子任务成功'));
            this.refreshGrid();
        }

      
    }
  
};
</script>
<style lang="less">
    .task-detail-registry__container{
        height: 500px;
        padding: 10px;
        overflow: auto;
        .title{
            font-size: 14px;
            font-weight: bold;
            color: #14161A;
        }
        .task-detail__charts{
            display: flex;
        }
        .detail-charts__item{
            flex: 1;
            margin: 10px;
        }
        .task__name{
            margin-bottom: 15px;
        }
        .table-data {
            height: calc(100% - 410px);
            width: 100%;
            .sfv-grid {
                /* border: none; */
                height: 100%;
                display: flex;
                flex-direction: column;

                .sfv-table {
                    flex: 1;
                }
            }
    
            .task-flex{
                display: flex;
                align-items: center;
            }
        }
    }
</style>
  